package com.fingard.text;

import sun.misc.*;

import java.io.IOException;

public class Base64Helper {

	// 加密  
    public static String getBase64(String str, String p_charset) {  
        byte[] b = null;  
        String s = null;  
        try {  
            b = str.getBytes(p_charset);  
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        if (b != null) {  
            s = new BASE64Encoder().encode(b);  
        }  
        return s;  
    }  
    //加密
    public static String  getBase64(byte[] b){
    	String str=null;
    	if(b!=null){
    		str = new BASE64Encoder().encode(b);
    	}
    	return str;
    }
    
  
    // 解密  
    public static String getFromBase64(String s, String p_charset) {  
        byte[] b = null;  
        String result = null;  
        if (s != null) {  
            BASE64Decoder decoder = new BASE64Decoder();
            try {  
                b = decoder.decodeBuffer(s);  
                result = new String(b, p_charset);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return result;  
    }

    //加密
    public static String encode(byte[] byteArray) {
        sun.misc.BASE64Encoder base64Encoder = new sun.misc.BASE64Encoder();
        return base64Encoder.encode(byteArray);
    }

    //解密
    public static byte[] decode(String base64EncodedString) {
        sun.misc.BASE64Decoder base64Decoder = new sun.misc.BASE64Decoder();
        try {
            return base64Decoder.decodeBuffer(base64EncodedString);
        } catch (IOException e) {
            return null;
        }
    }
}
